#coding=utf8
from uliweb import expose
from uliweb.orm import get_model

def __begin__():
    from uliweb import functions
    return functions.require_login()

@expose('/tfunctions/<int:task_id>')
def tasks_functions(task_id):
    """
    任务功能点列表
    """
    
    from uliweb.utils.generic import ListView, get_sort_field
    from uliweb.orm import get_model
    
    Task = get_model('tasks_develop')
    F = get_model('sysfunction')
    Functions = get_model('task_functions')
    C = get_model('sysfunctioncategory')
    
    order_by = get_sort_field(Functions) or []
    order_by = [F.c.category, F.c.function_code] + order_by

    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))

    def category(value, obj):
        if obj.function._category_:
            return obj.function.category.name
        else:
            return ''
        
    def function_code(value, obj):
        return obj.function.function_code
    
    fields_convert_map = {'category':category, 'function_code':function_code}
    
    condition = (Functions.c.task == int(task_id)) & (Functions.c.function==F.c.id)
    view = ListView(Functions, condition=condition, pagination=True,
        table_width=False, id='functions_table', fields_convert_map=fields_convert_map,
        order_by=order_by, rows_per_page=rows_per_page, pageno=pageno)
    if Functions.filter(condition).count() == 0:
        return json({'table':'', 'info':{'total':0}})
    return json(view.run(head=True, body=True))

@expose('/tfunctions/<int:task_id>/edit')
def tasks_functions_edit(task_id):
    """
    任务功能点列表编辑
    """
    Task = get_model('tasks_develop')
    task = Task.get(int(task_id))
    sys_id = task._task_sys_
    
    query = _create_query(tasks_functions_edit, sys_id)
    c = query.run()
    
    return {'task_id':task_id, 'query_form': query.form, 'flag':c.get('type', 'assign'), 'sys_id':task._task_sys_}

def _get_row_data(row):
    """
    row 是select的记录
    """
    from uliweb.orm import get_model

    TF = get_model('task_functions')
    C = get_model('sysfunctioncategory')
    if row.category:
        c = C.get(row.category)
        if c:
            category = unicode(c)
        else:
            category = ''
    else:
        category = ''
    if row.id:
        checked = 'checked'
    else:
        checked = ''
    if row.id:
        link = u"<a href='/tfunctions/update/%d' class='edit_function'>编辑</a>" % row.id
    else:
        link = ''
    d = {'id':row.id, 'function_id':row.function_id,
        'function':"<a href='/systems/functions/view/%d' title='%s'>%s(%s)</a>" % (row.function_id, row.function_name, row.function_code, row.function_name),
        'change_status':TF.change_status.get_display_value(row.change_status), 
        'open_status':TF.open_status.get_display_value(row.open_status), 
        'open_secverify':TF.open_secverify.get_display_value(row.open_secverify), 
        'test_point':row.test_point, 
        'checked':checked,
        'action_link':link,
        'category':'<span title="%s">%s</span>' % (category, category)
        }
    return d

def _get_row_data2(row):
    """
    row是Tasks_Functions记录
    """
    from uliweb.orm import get_model

    TF = get_model('task_functions')
    F = get_model('sysfunction')
    if row._function_:
        category = F.category.get_display_value(row.function.category)
    else:
        category = ''
    if row.id:
        checked = 'checked'
    else:
        checked = ''
    d = {'id':row.id, 
        'function_id':row._function_,
        'function':"<a href='/systems/functions/view/%d' title='%s'>%s(%s)</a>" % (row._function_, row.function.function_name, row.function.function_code, row.function.function_name),
        'change_status':TF.change_status.get_display_value(row.change_status), 
        'open_status':TF.open_status.get_display_value(row.open_status), 
        'open_secverify':TF.open_secverify.get_display_value(row.open_secverify), 
        'test_point':row.test_point, 
        'checked':checked,
        'action_link':u"<a href='/tfunctions/update/%d' class='edit_function'>编辑</a>" % row.id,
        'category':'<span title="%s">%s</span>' % (category, category)
        }
    return d

def _get_row_data3(row):
    """
    row是SysFunction记录
    """
    from uliweb.orm import get_model

    F = get_model('sysfunction')
    if row.category:
        category = unicode(row.category)
    else:
        category = ''
        
    d = {'id':'', 
        'function_id':row.id,
        'function':"<a href='/systems/functions/view/%d' title='%s'>%s(%s)</a>" % (row.id, row.function_name, row.function_code, row.function_name),
        'change_status':'', 
        'open_status':'', 
        'open_secverify':'', 
        'test_point':'', 
        'checked':'',
        'action_link':'',
        'category':'<span title="%s">%s</span>' % (category, category)
        }
    return d

def _create_query(url, sys_id):
    """
    创建查询View
    """
    from uliweb.orm import get_model
    from uliweb.utils.generic import QueryView
    from uliweb.form import UnicodeField, SelectField
    from uliweb.utils.generic import ReferenceSelectField
    
    C = get_model('sysfunctioncategory')
    type = SelectField('类型', choices=[('assigned', '已关联'), ('all', '全部'), ('unassigned', '未关联')], default='assigned')
    category = ReferenceSelectField(C, label='分类', condition=(C.c.system==sys_id))
    name = UnicodeField(label='名称')
    fields = [('type', type), ('category', category), ('name', name)] 
    query = QueryView('sysfunction', ok_url=url, fields=fields)
    return query

@expose('/tfunctions/<int:task_id>/list')
def tasks_functions_list(task_id):
    """
    任务功能点列表获取
    """
    from uliweb.orm import get_model, do_
    from sqlalchemy.sql import select, exists
    
    F = get_model('sysfunction')
    TF = get_model('task_functions')
    Task = get_model('tasks_develop')
    task = Task.get(int(task_id))
    sys_id = task._task_sys_

    query = _create_query(tasks_functions_edit, sys_id)
    c = query.run()
    
    flag = c.get('type')
    condition = None
    if c.get('category'):
        condition = (F.c.category == int(c['category'])) & condition
    if c.get('name'):
        condition = (F.c.function_name.like('%%' + c['name'] + '%%')) & condition
        
    fields = [F.c.id.label('function_id'), F.c.category,
                F.c.function_name, F.c.function_code,
                TF.c.id, TF.c.change_status, TF.c.open_status,
                TF.c.open_secverify, TF.c.test_point]

    get_result = _get_row_data
    if flag == 'assigned':
        results = do_(select(fields, 
                (F.c.system == sys_id) & (F.c.id==TF.c.function) & (TF.c.task == int(task_id)) & condition))
    elif flag == 'all':
        results = do_(select(fields, 
            (F.c.system == sys_id) & condition,
            from_obj=[F.table.outerjoin(TF.table, (F.c.id==TF.c.function) & (TF.c.task == int(task_id)))]))
    else:
        results = F.filter((F.c.system == sys_id) &
            ~F.c.id.in_(select([TF.c.function], TF.c.task == int(task_id))) & condition)
        get_result = _get_row_data3
    
    s = []
    for row in results:
        d = get_result(row)
        s.append(d)
    return json({'rows':s, 'size':len(s)})
    
@expose('/tfunctions/<int:task_id>/set')
def tasks_functions_set(task_id):
    """
    任务功能点更新
    """
    from uliweb.orm import get_model, do_

    F = get_model('sysfunction')
    TF = get_model('task_functions')

    action = request.POST.get('action')
    function_id = request.POST.get('function_id')

    d = {}
    flag = True
    message = u'处理成功'
    
    #关联功能点处理
    if action == 'assign':
        row = TF(function=int(function_id), task=int(task_id),
            open_status='1', open_secverify='1', change_status='1')
        row.save()
        d = _get_row_data2(row)
        return json({'success':flag, 'data':d})
    #去关联功能点
    elif action == 'unassign':
        row = TF.get((TF.c.function==int(function_id)) & (TF.c.task==int(task_id)))
        if row:
            row.delete()
        else:
            flag = False
            message = u'无此功能点'
        return json({'success':flag, 'message':message})
        
@expose('/tfunctions/update/<int:id>')
def tasks_functions_update(id):
    """
    修改任务关联的功能点
    """
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    
    TF = get_model('task_functions')
    obj = TF.get_or_notfound(int(id))
    
    view = EditView('task_functions', success_data=_get_row_data2, obj=obj,
        form_args={'action':request.path, 'html_attrs':{'id':'function_form'}}, 
        #success_data=_success_change_plan_handler, post_save=post_save,
    )
    return view.run(json_result=True)
    